// pages/play/run.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    count_down_number: 3,
    showMask: true,
    showGo: true,
    timer: null,
    timer2: null,
    step: 0,
    move: false,
    min: '00',
    hour: '0',
    second:'00',
    sudu: '00',
    speed: '0',
    i: 0,
    ag_time: 0,
    kaluli: 0.00,
    countAudio: null,
    updateStep: true,
    mp:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    // that.countTime()
    that.setData({
      km: options.km,
      time: options.time,
      status: options.status
    })
    if (!!options.hasOwnProperty('order_id')) {
      that.setData({
        order_id: options.order_id
      })
    }
    that.data.countAudio = wx.createInnerAudioContext();
    that.data.countAudio.src = 'https://resource.160nurse.com/canvas/healthy/mp3/countdown.mp3';
    let num = 3
    that.getWidth()
    that.getLocationData('start')
    console.log(that.data.count_down_number, getCurrentPages())
    if (that.data.status == 1) {
      that.getRunData('index.php?c=step&a=getOrder')
      that.setData({
        showMask: false,
        showGo: false
      })
    } else {
      that.data.countAudio.autoplay = true;
      that.data.countAudio.onPlay(() => {
        console.log('开始播放')
      });
      that.data.countAudio.onEnded(() => {
        console.log('播放结束')
        that.data.countAudio.destroy()
      });
      let timer = setInterval(function () {
        if (that.data.count_down_number > 1) {
          num--
          that.setData({
            count_down_number: num
          })
        } else {
          clearTimeout(timer)
          that.setData({
            showMask: false,
            showGo: true
          })
          setTimeout(function () {
            that.setData({
              showGo: false
            })
            that.getRunData('index.php?c=step&a=addOrder')
          }, 1000)
        }
      }, 1000)
    }
    // let num = 3
    // that.getWidth()
    // that.getLocationData('start')
    // if (options.status == 1) {
    //   that.getRunData('index.php?c=step&a=getOrder')
    //   that.setData({
    //     showMask: false,
    //     showGo: false
    //   })
    // } else {
    //   let timer = setInterval(function () {
    //     if (that.data.count_down_number > 1) {
    //       that.setData({
    //         count_down_number: num
    //       })
    //     num--
    //     } else {
    //       clearTimeout(timer)
    //       that.setData({
    //         showMask: false,
    //         showGo: true
    //       })
    //       setTimeout(function () {
    //         that.setData({
    //           showGo: false
    //         })
    //         that.getRunData('index.php?c=step&a=addOrder')
    //       }, 1000)
    //     }
    //   }, 1000)
    // }

  },
  getRunData: function (str) {
    let that = this
    // console.log('开始跑步，请求步数')
    wx.showLoading({
      title: '正在加载',
    })
    if (!wx.getStorageSync("openid")) {
      wx.login({
        success(res) {
          if (res.code) {
            wx.request({
              url: app.apiDomain + 'index.php?c=user&a=getopenid',
              data: {
                code: res.code
              },
              success: function (res) {
                let openid = res.data.data.openid
                wx.setStorageSync('openid', openid)
                wx.getWeRunData({
                  fail(res) {
                    wx.hideLoading({
                      title: '获取运动步数失败'
                    })
                    // console.log('getWeRunData failed', res);
                  },
                  success(res) {
                    wx.stopPullDownRefresh()
                    that.setData({
                      tongbu: false
                    })
                    // console.log('请求步数成功')
                    var encryptedData = res.encryptedData
                    let obj = {}
                    if (str.indexOf('addOrder') != -1) {
                      obj = {
                        encryptedData: res.encryptedData,
                        iv: res.iv,
                        openid: openid,
                        mileage: that.data.km,
                        // minute: that.data.time,
                        lng: that.data.longitude,
                        lat: that.data.latitude,
                        type: 2
                      }
                    } else {
                      obj = {
                        encryptedData: res.encryptedData,
                        iv: res.iv,
                        openid: openid,
                        mileage: that.data.km,
                        // minute: that.data.time,
                        order_id: that.data.order_id,
                        type: 2
                      }
                    }
                    wx.request({
                      url: app.apiDomain + str,
                      header: {
                        //设置参数内容类型为x-www-form-urlencoded
                        'content-type': 'application/x-www-form-urlencoded',
                        'Accept': 'application/json'
                      },
                      data: obj,
                      method: "POST",
                      success: function (res) {
                        // console.log('步数请求成功',res)
                        // 设置数据
                        that.setData({
                          kaluli: parseFloat(res.data.data.end_step / 20).toFixed(2),
                          current_km: res.data.data.end_step,
                          order_id: res.data.data.id,
                          lng: that.data.longitude,
                          lat: that.data.latitude
                        })
                        // 计算时间
                        let start_time = res.data.data.start_time * 1000
                        let steps = parseFloat(that.data.current_km / that.data.km).toFixed(3)
                        let step_progress = steps.substring(0, steps.toString().length - 1)
                        that.countTime(start_time)
                        that.drawCircle(step_progress)
                        wx.hideLoading()
                      },
                      fail() {
                        wx.hideLoading()
                      }
                    })
                  }
                });
              },
              fail: function (res) {
                wx.hideLoading()
                wx.showToast({
                  title: '请下拉刷新重试',
                  icon: 'none'
                })
                return false
              }
            })
          }
        }
      });
    } else {
      wx.getWeRunData({
        fail(res) {
          wx.hideLoading({
            title: '获取运动步数失败'
          })
          // console.log('getWeRunData failed', res);
        },
        success(res) {
          wx.stopPullDownRefresh()
          that.setData({
            tongbu: false
          })
          // console.log('请求步数成功')
          var encryptedData = res.encryptedData
          let obj = {}
          if (str.indexOf('addOrder') != -1) {
            obj = {
              encryptedData: res.encryptedData,
              iv: res.iv,
              openid: wx.getStorageSync("openid"),
              mileage: that.data.km,
              // minute: that.data.time,
              lng: that.data.longitude,
              lat: that.data.latitude,
              type: 2
            }
          } else {
            obj = {
              encryptedData: res.encryptedData,
              iv: res.iv,
              openid: wx.getStorageSync("openid"),
              mileage: that.data.km,
              // minute: that.data.time,
              order_id: that.data.order_id,
              type: 2
            }
          }
          wx.request({
            url: app.apiDomain + str,
            header: {
              //设置参数内容类型为x-www-form-urlencoded
              'content-type': 'application/x-www-form-urlencoded',
              'Accept': 'application/json'
            },
            data: obj,
            method: "POST",
            success: function (res) {
              // console.log('步数请求成功',res)
              // 设置数据
              that.setData({
                kaluli: parseFloat((res.data.data.end_step) / 20).toFixed(2),
                current_km: res.data.data.end_step,
                order_id: res.data.data.id,
                lng: that.data.longitude,
                lat: that.data.latitude
              })
              // 计算时间
              let start_time = res.data.data.start_time * 1000 + that.data.time * 60 * 1000
              let steps = parseFloat(that.data.current_km / that.data.km).toFixed(3)
              let step_progress = steps.substring(0, steps.toString().length - 1)
              that.countTime(start_time)
              that.drawCircle(step_progress)
              wx.hideLoading()
            },
            fail() {
              wx.hideLoading()
            }
          })
        }
      });
    }
  },
  getRun: function (str) {
    let that = this
    if (str.indexOf('end') != -1) {
      wx.showLoading({
        title: '正在结束',
      })
    }
    console.log('开始跑步，请求步数', wx.getStorageSync("openid"))
    if (!wx.getStorageSync("openid")) {
      console.log(11)
      wx.login({
      success(res) {
        if (res.code) {
          wx.request({
            url: app.apiDomain + 'index.php?c=user&a=getopenid',
            data: {
              code: res.code
            },
            success: function (res) {
              let openid = res.data.data.openid
              wx.getWeRunData({
                fail(res) {
                  // console.log('getWeRunData failed', res);
                },
                success(res) {
                  // console.log('请求步数成功')
                  var encryptedData = res.encryptedData
                  let obj = {}
                  if (str.indexOf('end') != -1) {
                    obj = {
                      lng: that.data.longitude,
                      lat: that.data.latitude,
                      encryptedData: res.encryptedData,
                      iv: res.iv,
                      openid: openid,
                      order_id: that.data.order_id,
                      type: 2
                    }
                  } else {
                    obj = {
                      encryptedData: res.encryptedData,
                      iv: res.iv,
                      openid: openid,
                      order_id: that.data.order_id,
                      type: 2
                    }
                  }
                  wx.request({
                    url: app.apiDomain + str,
                    header: {
                      //设置参数内容类型为x-www-form-urlencoded
                      'content-type': 'application/x-www-form-urlencoded',
                      'Accept': 'application/json'
                    },
                    data: obj,
                    method: "POST",
                    success: function (res) {
                      if (str.indexOf('getOrder') != -1) {
                        console.log('步数请求成功2', res)
                        if (res.data.data.end_step == res.data.data.start_step) {
                          that.setData({
                            updateStep: false
                          })
                        } else {
                          that.setData({
                            updateStep: true
                          })
                        }
                        that.setData({
                          tongbu: false
                        })
                        console.log('是Iphone?', that.data.updateStep)
                        // 设置数据
                        let current_km = res.data.data.end_step
                        that.setData({
                          kaluli: parseFloat((res.data.data.end_step) / 20).toFixed(2),
                          current_km: current_km
                        })
                        // 计算配速
                        let speed = parseFloat(that.data.current_km * 0.6 / that.data.ag_time).toFixed(2)
                        // console.log('配速', speed)
                        that.setData({
                          speed: speed.substring(0, speed.toString().indexOf('.')),
                          sudu: speed.substring(speed.toString().indexOf('.') + 1)
                        })
                        // 计算时间
                        if (that.data.current_km >= that.data.km){
                          that.drawCircle(1)
                          that.getLocationData('end')
                          wx.showToast({
                            title: '挑战结束',
                          })
                          clearInterval(that.data.timer2)
                        } else {
                          // that.getLocationData('start')
                          let steps = parseFloat(that.data.current_km / that.data.km).toFixed(3)
                          let step_progress = steps.substring(0, steps.toString().length - 1)
                          // that.countTime(start_time)
                          // console.log('进度', step_progress)
                          that.drawCircle(step_progress)
                        }
                      } else {
                        that.getLocationData('end')
                        wx.hideLoading()
                        // wx.showToast({
                        //   title: '挑战结束',
                        //   success: function () {
                            // wx.navigateTo({
                            //   url: './result?order_id=' + that.data.order_id,
                            // })
                            let time = res.data.data.end_time - res.data.data.start_time
                            let hour = parseInt(time / 60 / 60 % 24)
                            let min = parseInt(time / 60 % 60) < 10 ? '0' + parseInt(time / 60 % 60) : parseInt(time / 1000 / 60 % 60)
                            let sec = parseInt(time % 60) < 10 ? '0' + parseInt(time % 60) : parseInt(time % 60)
                            console.log('所用时间',hour, min, sec)
                            that.setData({
                              isopen: true,
                              isSuccess: res.data.data.status == 2 ? false : true,
                              hour_end: hour,
                              min_end: min,
                              sec_end: sec,
                              point: res.data.data.point
                            })
                            clearInterval(that.data.timer2)
                            // wx.navigateTo({
                            //   url: './result?order_id=' + that.data.order_id,
                            // })
                        //   }
                        // })
                      }
                    }
                  })
                }
              });
            }
          })
        } else {
          // console.log('登录失败！' + res.errMsg)
        }
      },
      fail(res) {
        wx.hideLoading()
        wx.showToast({
          title: '请下拉刷新重试',
          icon: 'none'
        })
        return false
      }
      });
    } else {
      wx.getWeRunData({
        fail(res) {
          // console.log('getWeRunData failed', res);
        },
        success(res) {
          // console.log('请求步数成功')
          var encryptedData = res.encryptedData
          let obj = {}
          if (str.indexOf('end') != -1) {
            obj = {
              lng: that.data.longitude,
              lat: that.data.latitude,
              encryptedData: res.encryptedData,
              iv: res.iv,
              openid: wx.getStorageSync("openid"),
              order_id: that.data.order_id,
              type: 2
            }
          } else {
            obj = {
              encryptedData: res.encryptedData,
              iv: res.iv,
              openid: wx.getStorageSync("openid"),
              order_id: that.data.order_id,
              type: 2
            }
          }
          wx.request({
            url: app.apiDomain + str,
            header: {
              //设置参数内容类型为x-www-form-urlencoded
              'content-type': 'application/x-www-form-urlencoded',
              'Accept': 'application/json'
            },
            data: obj,
            method: "POST",
            success: function (res) {
              if (str.indexOf('getOrder') != -1) {
                // console.log('步数请求成功', res)
                if (res.data.data.end_step == res.data.data.start_step && that.data.isIphone) {
                  that.setData({
                    updateStep: false
                  })
                } else {
                  that.setData({
                    updateStep: true
                  })
                }
                that.setData({
                  tongbu: false
                })
                // 设置数据
                let current_km = res.data.data.end_step
                that.setData({
                  kaluli: parseFloat(res.data.data.end_step / 20).toFixed(2),
                  current_km: current_km
                })
                // 计算配速
                let speed = parseFloat(that.data.current_km * 0.6 / that.data.ag_time).toFixed(2)
                console.log('配速', that.data.current_km, that.data.ag_time)
                that.setData({
                  speed: speed.substring(0, speed.toString().indexOf('.')),
                  sudu: speed.substring(speed.toString().indexOf('.') + 1)
                })
                // 计算时间
                if (that.data.current_km >= that.data.km) {
                  that.drawCircle(1)
                  that.getLocationData('end')
                  wx.showToast({
                    title: '挑战结束',
                  })
                  clearInterval(that.data.timer2)
                } else {
                  // that.getLocationData('start')
                  let steps = parseFloat(that.data.current_km / that.data.km).toFixed(3)
                  let step_progress = steps.substring(0, steps.toString().length - 1)
                  // that.countTime(start_time)
                  // console.log('进度', step_progress)
                  that.drawCircle(step_progress)
                }
              } else {
                that.getLocationData('end')
                wx.hideLoading()
                // wx.showToast({
                //   title: '挑战结束',
                //   success: function () {
                    // wx.navigateTo({
                    //   url: './result?order_id=' + that.data.order_id,
                    // })
                    let year = new Date().getFullYear()
                    let month = new Date().getMonth() + 1
                    let date = new Date().getDate()
                    let agoTime = new Date(year + '/' + month + '/' + date + ' 00:00:00').getTime()
                    let time = res.data.data.end_time - parseInt(agoTime / 1000)
                    let hour = parseInt(time / 60 / 60 % 24)
                    let min = parseInt(time / 60 % 60) < 10 ? '0' + parseInt(time / 60 % 60) : parseInt(time / 60 % 60)
                    let sec = parseInt(time % 60) < 10 ? '0' + parseInt(time % 60) : parseInt(time % 60)
                    console.log('所用时间', hour, min, sec)
                    that.setData({
                      isopen: true,
                      isSuccess: res.data.data.status == 2 ? false : true,
                      hour_end: hour,
                      min_end: min,
                      sec_end: sec
                    })
                    clearInterval(that.data.timer2)
                    // wx.navigateTo({
                    //   url: './result?order_id=' + that.data.order_id,
                    // })
                //   }
                // })
              }
            }
          })
        }
      });
    }
  },
  // 倒计时
  timeCount: function() {
    let time = 30
    if (time < 60) {
      that.setData({
        min: time,
        second: 0,
        hour: 0
      })
    } else {
      let h = parseInt(time / 60)
      let m = time - h * 60
      that.setData({
        min: m,
        second: 0,
        hour: h
      })
    }
  },
  tongbu:function () {
    let that = this
    that.setData({
      tongbu: true
    })
    that.getRun('index.php?c=step&a=getOrder')
  },
  countTime: function (s_time){
    var that = this
    let year = new Date().getFullYear()
    let month = new Date().getMonth() + 1
    let date = new Date().getDate()
    let curTime = new Date(year + '/' + month + '/' + date + ' 23:30:00').getTime()
    let agoTime = new Date(year + '/' + month + '/' + date + ' 00:00:00').getTime()
    let beginTime = new Date().getTime()
    let time = curTime - beginTime
    let ag_time = parseInt((beginTime - agoTime) / 1000)
    let i = parseInt(time / 1000)
    that.setData({
      i: that.data.time * 60 - i,
      ag_time: ag_time
    })
    let hour = parseInt(time / 1000 / 60 / 60 % 24)
    let min = parseInt(time / 1000 / 60 % 60)
    let sec = parseInt(time / 1000 % 60)
    that.data.timer2 = setInterval(function() {
      // console.log(sec)
      if (sec <= 0) {
        if (min > 0) {
          min--
          sec = 59
        } else {
          if (hour > 0) {
            hour--
            min=59
            sec=59
          } else {
            sec = 0
            min = 0
            hour = 0
            // 倒计时结束hour=0 sec = 0 min = 0
            clearInterval(that.data.timer2)
            that.getRun('index.php?c=step&a=endOrder')
          }
        }
      } else {
        sec--
        // console.log(that.data.isIphone)
        if (!that.data.isIphone) {
          if (sec % 5 == 0) {
            that.getRun('index.php?c=step&a=getOrder')
          }
        } else {
          if (sec % 25 == 0) {
            that.getRun('index.php?c=step&a=getOrder')
          }
        }
      }
      that.setData({
        hour,
        min: min < 10 ? '0' + min : min,
        second: sec < 10 ? '0' + sec: sec,
        i: i
      })
      // console.log(hour, min, sec)
    },1000)
  },
  getLocationData: function (str) {
    let that = this
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        // console.log('速度', res)
        if (str == 'start') {
          that.setData({
            longitude: res.longitude,
            latitude: res.latitude
          })
        } else {
          that.setData({
            longitude2: res.longitude,
            latitude2: res.latitude
          })
        }
      },
      fail: function () {
        if (str == 'start') {
          that.setData({
            longitude: '',
            latitude: ''
          })
        } else {
          that.setData({
            longitude2: '',
            latitude2: ''
          })
        }
      }
    })
  },
  getWidth: function () {
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          unit: res.screenWidth / 100,
          sysWidth: res.screenWidth
        })
      }
    })
  },
  drawCircle: function (step) {
    var that = this
    let unit = that.data.unit
    let width = that.data.sysWidth
    var ctx = wx.createCanvasContext('km_progress')
    ctx.setLineWidth(3.2*unit) 
    ctx.setStrokeStyle('#00D2C3')
    ctx.setLineCap('round')
    ctx.beginPath()
    if (step > 0) {
      ctx.arc(32.53 * unit, 32.53 * unit, 30.93 * unit, Math.PI / 2, step * 2 * Math.PI +  Math.PI/2, false)
    }
    ctx.stroke()
    ctx.draw()
  },
  // 长按结束
  long_tap: function (e) {
    var that = this
    // console.log('长按')
    that.drawCanvasbg()
    that.data.step += 0.1
    that.drawProgress(that.data.step)
    that.setData({
      isScale: true
    })
    var ctx = wx.createCanvasContext('km_progress')
    var ctx2 = wx.createCanvasContext('canvas_bg')
    ctx.transform(1.1, 1.1, 0, 0, 0, 0)
    ctx2.transform(1.1, 1.1, 0, 0, 0, 0)
    that.data.timer = setInterval(function () {
      if (that.data.step <= 2) {
        that.data.step += 0.1
        that.drawProgress(that.data.step)
      } else {
        clearInterval(that.data.timer)
        // 触发暂停
        // 结束后跳转页面
        that.setData({
          isScale: false
        })
        that.end_tap()
        that.getRun('index.php?c=step&a=endOrder')
      }
    }, 100)
  },
  end_tap: function () {
    var ctx = wx.createCanvasContext('canvas_bg')
    var that = this
    that.setData({
      step: 0,
      isScale: false
    })
    that.drawProgress(that.data.step)
    ctx.setStrokeStyle('#fff')
    ctx.draw()
    // ctx.clearRect(0,0, 100, 100)
    clearInterval(that.data.timer)
  },
  drawCanvasbg: function () {
    var that = this
    let unit = that.data.unit
    var ctx = wx.createCanvasContext('canvas_bg')
    ctx.setLineWidth(3)
    ctx.setStrokeStyle('rgb(223,97,0)')
    ctx.setLineCap('round')
    ctx.beginPath();
    ctx.arc(14.08 * unit, 14.08 * unit, 12.8 * unit, 0, 2 * Math.PI, false);
    ctx.stroke();
    ctx.draw();
  },
  drawProgress: function (step) {
    var that = this
    var ctx = wx.createCanvasContext('canvas_progress')
    ctx.setLineWidth(3)
    ctx.setStrokeStyle('#fff')
    ctx.setLineCap('round')
    ctx.beginPath()
    let unit = that.data.unit
    if (step >= 0) {
      ctx.arc(14.08 * unit, 14.08 * unit, 12.8 * unit, -Math.PI / 2, step * Math.PI - Math.PI / 2, false)
    }
    ctx.stroke()
    ctx.draw()
  },
  movePage: function () {
    var that = this
    that.data.status = 1
    wx.navigateTo({
      url: './map?long=' + that.data.longitude + '&lati=' + that.data.latitude + '&long2=' + that.data.longitude2 + '&lati2=' + that.data.latitude2,
    })
  },
  goto: function () {
    let that = this
    wx.navigateTo({
      url: './result?order_id=' + that.data.order_id,
    })
  },
  onShareAppMessage: function () {
    var nickName = '';
    var userId = 0;
    try {
      nickName = wx.getStorageSync('nickname');
      userId = wx.getStorageSync('user_id');
    } catch (e) { }
    return {
      path: "/pages/play/index?user_id=" + userId,
      title: '运动挑战，让您的每一步充满激情。',
      imageUrl: app.resourceDomain + 'canvas/healthy/img/play/play_tz.png'
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    app.SystemInfo(this)
    console.log(this.isIphone)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    console.log('亮屏')
    console.log(that.data.status, that.data.mp)
    if (that.data.status == 1 && !that.data.mp) {
      console.log('亮屏')
      that.data.mp = true
      that.getRunData('index.php?c=step&a=getOrder')
      // that.setData({
      //   showMask: false,
      //   showGo: false
      // })
    }
    if (that.data.status == 0) {
      that.setData({
        status: 1
      })
    }
    // let num = 3
    // that.getWidth()
    // that.getLocationData('start')
    // console.log(that.data.count_down_number,getCurrentPages())
    // if (that.data.status == 1) {
    //   that.getRunData('index.php?c=step&a=getOrder')
    //   that.setData({
    //     showMask: false,
    //     showGo: false
    //   })
    // } else {
    //   that.data.countAudio.autoplay = true;
    //   that.data.countAudio.onPlay(() => {
		// 		console.log('开始播放')
		// 	});
    //   that.data.countAudio.onEnded(() => {
		// 		console.log('播放结束')
    //     that.data.countAudio.destroy()
		// 	});
    //   let timer = setInterval(function () {
    //     if (that.data.count_down_number > 1) {
    //       num--
    //       that.setData({
    //         count_down_number: num
    //       })
    //     } else {
    //       clearTimeout(timer)
    //       that.setData({
    //         showMask: false,
    //         showGo: true
    //       })
    //       setTimeout(function () {
    //         that.setData({
    //           showGo: false
    //         })
    //         that.getRunData('index.php?c=step&a=addOrder')
    //       }, 1000)
    //     }
    //   }, 1000)
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this
    console.log('灭屏')
    clearInterval(that.data.timer2)
    that.setData({
      mp: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that = this
    that.getRunData('index.php?c=step&a=getOrder')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
})